package com.guli.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.order.client.EduClient;
import com.guli.order.client.UcenterClient;
import com.guli.order.entity.Order;
import com.guli.order.mapper.OrderMapper;
import com.guli.order.service.OrderService;
import com.guli.order.utils.OrderNoUtil;
import com.guli.utils.UcenterMember;
import com.guli.utils.vo.OrderCourseWebVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author ZhaoZhenyu
 * @since 2022-10-04
 */

@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private EduClient eduClient;

    @Autowired
    private UcenterClient ucenterClient;

    @Override
    public String saveOrder(String courseId, String memberId) {

        //远程调用课程服务，根据课程id获取课程信息
        OrderCourseWebVo orderCourseWebVo = eduClient.getCourseInfoDto(courseId);

        //远程调用用户服务，根据用户id获取用户信息
        UcenterMember ucenterMember = ucenterClient.getInfo(memberId);

        Order order = new Order();
        order.setOrderNo(OrderNoUtil.getOrderNo());
        order.setCourseId(courseId);
        order.setCourseTitle(orderCourseWebVo.getTitle());
        order.setCourseCover(orderCourseWebVo.getCover());
        order.setTeacherName(orderCourseWebVo.getTeacherName());
        order.setTotalFee(orderCourseWebVo.getPrice());
        order.setMemberId(memberId);
        order.setMobile(ucenterMember.getMobile());
        order.setNickname(ucenterMember.getNickname());
        order.setStatus(0);
        order.setPayType(1);

        // 是否有重复订单：courseId 与 memberId都一样的
        Integer count = baseMapper.selectCount(new QueryWrapper<Order>().eq("course_id", courseId).eq("member_id", memberId));
        if (count == 0) {
            baseMapper.insert(order);
        }else {         // 有重复订单 覆盖
            baseMapper.update(order,new QueryWrapper<Order>().eq("course_id", courseId).eq("member_id", memberId));
        }
        return order.getOrderNo();
    }

}
